package com.zeen.wima.update;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zeen.wima.R;

public class UpdateView extends LinearLayout implements DownloadTask.PluginView {

	DownloadTask loadTask;
	Context context;
	ProgressBar progressBar;
	InstallList list;
	TextView name,desc;
	LinearLayout.LayoutParams layout;

	
	public UpdateView(Context context, DownloadTask p) {
		super(context);
		list = (InstallList) context;
		setLayoutParams(new ListView.LayoutParams(
				ListView.LayoutParams.FILL_PARENT,
				ListView.LayoutParams.WRAP_CONTENT));
		loadTask = p;
		loadTask.setView(this);
		this.context = context;
		layout = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		LayoutInflater vi = (LayoutInflater) (context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
		View v = vi.inflate(R.layout.update_app_view, null);
		name = (TextView) v.findViewById(R.id.pluginName);
		progressBar = (ProgressBar) v.findViewById(R.id.loadingProgressBar);
		progressBar.setMax(loadTask.getInfo().getSize());
		name.setText(loadTask.getInfo().getName());
		this.removeAllViews();
		this.addView(v, layout);
		loadTask.download();

	}

	
	
	@Override
	public void onDownloadFinished(String path) {
		LayoutInflater vi = (LayoutInflater) (context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
		View v = vi.inflate(R.layout.plugin, null);
		TextView name = (TextView) v.findViewById(R.id.pluginName);
		name.setText(loadTask.getInfo().getName());
		TextView desc = (TextView) v.findViewById(R.id.pluginDescription);
		desc.setText(loadTask.getInfo().getDescription());
		Button install = (Button) v.findViewById(R.id.installButton);
		this.removeAllViews();
		this.addView(v, layout);
		install.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startInstall();
			}
		});
	}

	private void startInstall() {
		list.onInstall(loadTask);
		try {
			Uri appPackage = Uri.fromFile(new File(loadTask.getSetupPath()));
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(appPackage,
					"application/vnd.android.package-archive");
			// context.startActivity(intent);
			list.startActivityForResult(intent, 0);
		} catch (Exception e) {

		}
		// context.getPackageManager().installPackage(appPackage, this,
		// PackageManager.REPLACE_EXISTING_PACKAGE);
	}

	@Override
	public void onProgressUpdate(int value) {
		if (progressBar != null) {
			progressBar.setProgress(value);
		}
	}
}
